package com.hhp.cloud.shop.common.core.result;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
//import com.fasterxml.jackson.core.JsonProcessingException;
//import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hhp.cloud.shop.common.core.enums.BizCodeEnume;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 自定义返回数据
 * @author: hhp
 * @date: 2021/11/18 15:30
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class R<T> extends HashMap<String, Object> implements Serializable {

    public R setData(T data){
        put("data",data);
        return this;
    }

    public R() {
        put("code", BizCodeEnume.SUCCESS.getCode());
        put("msg", BizCodeEnume.SUCCESS.getMsg());
    }

    public static R error() {
        return error(HttpStatus.HTTP_INTERNAL_ERROR, "未知异常，请联系管理员");
    }

    public static R error(String msg) {
        return error(HttpStatus.HTTP_INTERNAL_ERROR, msg);
    }

    public static R error(int code, String msg) {
        R r = new R();
        r.put("code", code);
        r.put("msg", msg);
        return r;
    }

    public static R error(BizCodeEnume bizCodeEnume, String msg) {
        R r = new R();
        r.put("code", bizCodeEnume.getCode());
        r.put("msg", msg);
        return r;
    }

    public static R error(BizCodeEnume bizCodeEnume) {
        R r = new R();
        r.put("code", bizCodeEnume.getCode());
        r.put("msg", bizCodeEnume.getMsg());
        return r;
    }

    public static R ok(String msg) {
        R r = new R();
        r.put("msg", msg);
        return r;
    }

    public static <T> R<T> trial(T data){
        if (data instanceof Boolean && Boolean.FALSE.equals(data)) {
            return error(BizCodeEnume.UNKNOW_EXCEPTION);
        }else{
            return ok().setData(data);
        }
    }

    public static R ok(Map<String, Object> map) {
        R r = new R();
        r.putAll(map);
        return r;
    }

    public static R ok() {
        return new R();
    }

    public R put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    //指定从哪个字段取值
    public <T> T getData(String key, TypeReference<T> typeReference) {
        Object data = get(key);//默认是map
        String jsonString = JSONUtil.toJsonStr(data);
        return JSONUtil.toBean(jsonString, typeReference, true);
    }

    public <T> T getData(TypeReference<T> typeReference) {
        Object data = get("data");//默认是map
        String jsonString = JSONUtil.toJsonStr(data);
        return JSONUtil.toBean(jsonString, typeReference, true);
    }

    public Integer getCode(){
        return (Integer) this.get("code");
    }
}
